package com.jrx.anytxn.feign.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import okhttp3.ConnectionPool;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.concurrent.TimeUnit;

/**
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @author Yeoman
 * @description
 * @create 2019/9/19 下午3:58
 **/
@Configuration
@AutoConfigureBefore(FeignAutoConfiguration.class)
@ConditionalOnClass(Feign.class)
public class FeignOkHttpConfig {

    /**
     * 过滤器中可以处理很多事情
     */
//    @Autowired
//    OkHttpInterceptor okHttpInterceptor;

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        return new okhttp3.OkHttpClient.Builder()
                // 设置读超时
                .readTimeout(60, TimeUnit.SECONDS)
                // 设置连接超时
                .connectTimeout(60, TimeUnit.SECONDS)
                // 设置写超时
                .writeTimeout(120, TimeUnit.SECONDS)
                //是否自动重连(这个需要研究下,防止有风险)
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
//                .addInterceptor(okHttpInterceptor)
                .build();
    }

    @Bean
    public Decoder springDecoder() {
        return new SpringDecoder(converter());
    }

    @Bean
    public Encoder springEncoder(){
        return new SpringEncoder(converter());
    }

    private ObjectFactory<HttpMessageConverters> converter() {
        return () -> new HttpMessageConverters(new MappingJackson2HttpMessageConverter(objectMapper()));
    }

    private ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper;
    }
}
